package com.dobby.live;

import com.pili.Configuration;
import com.pili.Hub;
import com.pili.PiliException;
import com.pili.Stream;
import com.qiniu.Credentials;
import org.apache.log4j.Logger;

/**
 * Created by liguoqing on 2016/5/28.
 */
public class LiveKit {

    private static Logger logger = Logger.getLogger(LiveKit.class);

    // Replace with your keys here
    //public static final String ACCESS_KEY = "GhQN3EyFbETBTwoz7D8-PbfXCUz3ANof_Ap5ffRX";
    //public static final String SECRET_KEY = "BvFhOhori8jpEzPqW5FJpAi7j04qLJYjUWftiQ_T";

    // Replace with your hub name
    //public static final String HUB_NAME = "dolooklive";

    static {
        Configuration.getInstance().setAPIHost("pili-lte.qiniuapi.com");
    }

    private static Credentials credentials = new Credentials(QiniuConfig.ACCESS_KEY, QiniuConfig.SECRET_KEY);
    private static Hub hub = new Hub(credentials, QiniuConfig.HUB_NAME);

    /**
     * 新建流
     * @return
     */
    public static Stream createStream() {
        Stream stream = null;
        // Create a new Stream
        String title           = null;     // optional, auto-generated as default
        String publishKey      = null;     // optional, auto-generated as default
        String publishSecurity = null;     // optional, can be "dynamic" or "static", "dynamic" as default
        try {
            stream = hub.createStream(title, publishKey, publishSecurity);
             /*
            {
                "id":"z1.test-hub.55d97350eb6f92638c00000a",
                "createdAt":"2015-08-22T04:54:13.539Z",
                "updatedAt":"2015-08-22T04:54:13.539Z",
                "title":"55d97350eb6f92638c00000a",
                "hub":"test-hub",
                "disabled":false,
                "publishKey":"ca11e07f094c3a6e",
                "publishSecurity":"dynamic",
                "hosts":{
                    "publish":{
                        "rtmp":"ey636h.publish.z1.pili.qiniup.com"
                     },
                     "live":{
                         "hdl":"ey636h.live1-hdl.z1.pili.qiniucdn.com",
                         "hls":"ey636h.live1-hls.z1.pili.qiniucdn.com",
                         "rtmp":"ey636h.live1-rtmp.z1.pili.qiniucdn.com"
                     },
                     "playback":{
                         "hls":"ey636h.playback1.z1.pili.qiniucdn.com"
                     }
                 }
             }
             */
            logger.info("hub.createStream:");
            logger.info(stream.toJsonString());
        } catch (PiliException e) {
            e.printStackTrace();
        }
        return stream;
    }


    /**
     * 获取流
     * @param streamId
     * @return
     */
    public static Stream getStream(String streamId) {
        Stream stream = null;
        // get Stream
        try {
            stream = hub.getStream(streamId);
            logger.info("hub.getStream:");
            logger.info(stream.toJsonString());
        } catch (PiliException e) {
            e.printStackTrace();
        }
        return stream;
    }

    /**
     * 更新流
     * @return
     */
    public static Stream updateStream(String streamId) {
        Stream stream = null;
        // Update a Stream
        String newPublishKey       = "new_secret_words"; // optional
        String newPublishSecurity  = "static";           // optional, can be "dynamic" or "static"
        boolean newDisabled        = true;               // optional, can be "true" of "false"
        try {
            Stream newStream = stream.update(newPublishKey, newPublishSecurity, newDisabled);
            /*
            {
                "id":"z1.test-hub.55d80075e3ba5723280000d2",
                "createdAt":"2015-08-22T04:54:13.539Z",
                "updatedAt":"2015-08-22T01:53:02.738973745-04:00",
                "title":"55d80075e3ba5723280000d2",
                "hub":"test-hub",
                "disabled":true,
                "publishKey":"new_secret_words",
                "publishSecurity":"static",
                "hosts":{
                    "publish":{
                        "rtmp":"ey636h.publish.z1.pili.qiniup.com"
                     },
                     "live":{
                         "hdl":"ey636h.live1-hdl.z1.pili.qiniucdn.com",
                         "hls":"ey636h.live1-hls.z1.pili.qiniucdn.com",
                         "rtmp":"ey636h.live1-rtmp.z1.pili.qiniucdn.com"
                     },
                     "playback":{
                         "hls":"ey636h.playback1.z1.pili.qiniucdn.com"
                     }
                 }
             }
         */
            logger.info("Stream update()");
            logger.info(newStream.toJsonString());
            stream = newStream;
        } catch (PiliException e) {
            e.printStackTrace();
        }
        return stream;
    }


    /**
     * 列出所有的流
     * @return
     */
    public static Stream.StreamList getStreamList(String status) {
        Stream.StreamList streamList = null;
        try {
            streamList = hub.listStreams(status,null, Integer.MAX_VALUE,null);
            logger.info("hub listStreams()");
            for(Stream stream : streamList.getStreams()) {
                logger.info("streamId:"+stream.getStreamId());
            }
        } catch (PiliException e) {
            e.printStackTrace();
        }
        return streamList;
    }

    /**
     * 获取RTMP 推流地址
     */
    public static String getRtmpPublishUrl(String streamId) {
        // Generate RTMP publish URL
        String publishUrl = null;
        try {
            Stream stream = hub.getStream(streamId);
            publishUrl = stream.rtmpPublishUrl();
            logger.info("Stream rtmpPublishUrl()");
            logger.info(publishUrl);
        } catch (PiliException e) {
            e.printStackTrace();
        }

        return publishUrl;
    }



    /**
     * 获取RTMP直播地址
     */
    public static String getRtmpLiveUrl(String streamId) {
        String originUrl = null;
        try {
            Stream stream = hub.getStream(streamId);
            // Generate RTMP live play URLs
            originUrl = stream.rtmpLiveUrls().get(Stream.ORIGIN);
            logger.info("Stream rtmpLiveUrls()");
            logger.info(originUrl);
        } catch (PiliException e) {
            e.printStackTrace();
        }
        return originUrl;
    }


    /**
     * 获取hls直播地址
     */
    public static String getHlsLiveUrl(String streamId) {
        String originLiveHlsUrl = null;
        try {
            Stream stream = hub.getStream(streamId);
            // Generate HLS play URLs
            originLiveHlsUrl = stream.hlsLiveUrls().get(Stream.ORIGIN);
            logger.info("Stream hlsLiveUrls()");
            logger.info(originLiveHlsUrl);
        } catch (PiliException e) {
            e.printStackTrace();
        }
        return originLiveHlsUrl;
    }


    /**
     * 获取Http-flv 直播地址
     */
    public static String getHttpFlvLiveUrl(String streamId) {
        String originLiveFlvUrl = null;
        try {
            Stream stream = hub.getStream(streamId);
            // Generate Http-Flv live play URLs
            originLiveFlvUrl = stream.httpFlvLiveUrls().get(Stream.ORIGIN);
            logger.info("Stream httpFlvLiveUrls()");
            logger.info(originLiveFlvUrl);
        } catch (PiliException e) {
            e.printStackTrace();
        }
        return originLiveFlvUrl;
    }


    /**
     * 禁播
     */
    public static boolean disableStream(String streamId) {
        boolean flag = true;
        try {
            Stream stream = hub.getStream(streamId);
            Stream disabledStream = stream.disable();
            logger.info("Stream disable()");
            logger.info(disabledStream.isDisabled());
        } catch (PiliException e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }


    /**
     * 重新激活
     */
    public static boolean enableStream(String streamId) {
        boolean flag = true;
        try {
            Stream stream = hub.getStream(streamId);
            Stream disabledStream = stream.enable();
            logger.info("Stream enable()");
            logger.info(disabledStream.isDisabled());
        } catch (PiliException e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }


    /**
     * 查询主播状态
     */
    public static Stream.Status getStreamStatus(String streamId) {
        Stream.Status status = null;
        try {
            Stream stream = hub.getStream(streamId);
            status = stream.status();
             /*
            {
                "addr":"222.73.202.226:2572",
                "startFrom": "2015-09-10T05:58:10.289+08:00",
                "status":"disconnected",
                "bytesPerSecond":0,
                "framesPerSecond":{
                    "audio":0,
                    "video":0,
                    "data":0
                 }
             }
            */
            logger.info("Stream status()");
            logger.info(status.toString());
        } catch (PiliException e) {
            e.printStackTrace();
        }
        return status;
    }


    /**
     * 获取流的片段
     * @return
     */
    public static Stream.SegmentList getSegmentList(String streamId) {
        Stream.SegmentList segmentList = null;
        // Get Stream segments
        long start = 0;    // optional, in second, unix timestamp
        long end   = 0;    // optional, in second, unix timestamp
        int limit  = 0;    // optional, int
        try {
            Stream stream = hub.getStream(streamId);
            segmentList = stream.segments(start, end, limit);
            logger.info("The earliest data of stream:" + segmentList.getStart()
                    + ",the latest data of stream:" + segmentList.getEnd());
            logger.info("The duration of the current segment:" + segmentList.getDuration());
            logger.info("Stream segments()");
            for (Stream.Segment segment : segmentList.getSegmentList()) {
                logger.info("start:" + segment.getStart() + ",end:" + segment.getEnd());
            }
        } catch (PiliException e) {
            e.printStackTrace();
        }
        return segmentList;
    }


    /**
     * 获取hls回放地址
     * @return
     */
    public static String getHlsPlaybackUrl(String streamId, long start, long end) {
        String hlsPlaybackUrl = null;
        // Generate HLS playback URLs
        // long startHlsPlayback     = 1467190276;  // required, in second, unix timestamp
        // long endHlsPlayback       = 1467801131;  // required, in second, unix timestamp
        try {
            Stream stream = hub.getStream(streamId);
            hlsPlaybackUrl = stream.hlsPlaybackUrls(start, end).get(Stream.ORIGIN);
            logger.info("Stream hlsPlaybackUrls()");
            logger.info(hlsPlaybackUrl);
        } catch (PiliException e) {
            e.printStackTrace();
        }
        return hlsPlaybackUrl;
    }


    /**
     * 截图
     * @return
     */
    public static Stream.SnapshotResponse getSnapshotResponse(String streamId) {
        Stream.SnapshotResponse response = null;
        // Snapshot Stream
        String format    = "jpg";                      // required
        String name      = "imageName" + "." + format; // required
        long time        = 0;                 // optional, in second, unix timestamp
        String notifyUrl = null;                       // optional
        try {
            Stream stream = hub.getStream(streamId);
            response = stream.snapshot(name, format, time, notifyUrl);
            logger.info("Stream snapshot()");
            logger.info(response.toString());
        } catch (PiliException e) {
            e.printStackTrace();
        }
        return response;
    }


    /**
     * 转存
     */
    public static Stream.SaveAsResponse saveAs(String streamId){
        Stream.SaveAsResponse response = null;
        String saveAsFormat    = "mp4";                            // required
        String saveAsName      = "videoName" + "." + saveAsFormat; // required
        long saveAsStart       = 1464590661;                       // required, in second, unix timestamp
        long saveAsEnd         = 1464591274;                       // required, in second, unix timestamp
        String saveAsNotifyUrl = null;                             // optional
        try {
            Stream stream = hub.getStream(streamId);
            response = stream.saveAs(saveAsName, saveAsFormat, saveAsStart, saveAsEnd);
            logger.info("Stream saveAs()");
            logger.info(response.toString());
        } catch (PiliException e) {
            e.printStackTrace();
        }
        return response;
    }


    /**
     * 删除流
     */
    public static boolean deleteStream(String streamId){
        // Delete a Stream
        boolean flag = true;
        try {
            Stream stream = hub.getStream(streamId);
            String res = stream.delete();
            logger.info("Stream delete()");
            logger.info(res);
            // No Content
        } catch (PiliException e) {
            flag = false;
            e.printStackTrace();
        }
        return true;
    }

    public static void main(String[] args) {
        String streamId = "z1.dolooklive.57493e711013855b28039c86";
        Stream.Status status = LiveKit.getStreamStatus(streamId);
        System.out.println(status.toString());
    }
}
